<script setup lang="ts">
import {
  createRechargeOrderApi,
  getBalanceApi,
  getHasPayPasswordApi,
  getWalletListApi,
  payRechargeApi,
} from '@/services/wallet'
import { useMemberStore } from '@/stores'
import type { balanceType } from '@/types/component'
import { Toast } from '@/utils/tools'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
// 箭头 由于直接写箭头程序报错 只能赋值变量
const str = ref('<')
// 获取胶囊的距离
const top = ref('') //上方距离
const pageheight = ref('') //整个导航栏高度
const height = ref('') //实际导航栏高度
const memberStore = useMemberStore()

// 账户余额
const balanceInfo = ref<balanceType>({
  totalBalance: '0.00',
  balance: '0.00',
  giftGold: '0.00',
  firstStored: 0,
})

// 确认用户协议
let classIcon = ref('icon-ring')

/**
 * * iconSwiper 触发用户协议
 */
const iconSwiper = () => {
  if (classIcon.value === 'icon-ring') {
    classIcon.value = 'icon-checked'
  } else {
    classIcon.value = 'icon-ring'
  }
}

// 显示隐藏

const isOpen = ref<boolean>(false)

// 去明细页面
const goRecords = () => {
  uni.navigateTo({
    url: '/pagesWallet/rechargeRecords/rechargeRecords',
  })
}
// 去支付密码页面
const goPayPassword = () => {
  const isSetting = hasPayPassword.value ? 0 : 1
  uni.navigateTo({
    url: '/pagesWallet/paymentPassword/paymentPassword?isSetting=' + isSetting,
  })
}

// 获取用户钱包余额
const getBalance = async () => {
  const res = await getBalanceApi()
  if (res.code === 200) {
    balanceInfo.value = res.data || {}
    memberStore.setBalanceInfo(res.data)
  }
}

// 获取用户是否存在支付密码
const hasPayPassword = ref<boolean>(false)
const getHasPayPassword = async () => {
  const res = await getHasPayPasswordApi()
  if (res.code === 200) {
    hasPayPassword.value = res.data
    memberStore.setHasPayPassword(res.data)
  }
}

// 选择储蓄项
const checkedIndex = ref<number>(0)
const datalist = ref<any[]>([])
const firstStoredActivity = ref<any>({})
const activityImg = ref(
  'https://yuefanpai.oss-cn-hangzhou.aliyuncs.com/miniapp/money.png',
)

// 获取储值列表
const getWalletList = async () => {
  const res = await getWalletListApi()
  if (res.code === 200) {
    datalist.value = res?.data?.storedActivity || []
    firstStoredActivity.value = res?.data?.firstStoredActivity || {}
    activityImg.value =
      res?.data?.activityImg ||
      'https://yuefanpai.oss-cn-hangzhou.aliyuncs.com/miniapp/no-activity.png'
  }
}

const handleChecked = (index: number) => {
  checkedIndex.value = index
}

const loading = ref<boolean>(false)

// 立即充值
const handleRecharge = async () => {
  if (classIcon.value === 'icon-ring') {
    Toast('请先阅读并同意储值协议')
    return
  }
  loading.value = true
  const res = await createRechargeOrderApi({
    activityDetailId: currentItem.value.id,
    activityId: currentItem.value.activityId,
  })
  if (res.code === 200) {
    const ret = await payRechargeApi({ orderSn: res.data })
    if (ret.code === 200) {
      wx.requestPayment({
        timeStamp: ret.data.timeStamp + '',
        nonceStr: ret.data.nonceStr,
        package: ret.data.packageValue,
        signType: ret.data.signType,
        paySign: ret.data.paySign,
        success: () => {
          if (hasPayPassword.value) {
            Toast('充值成功')
            getBalance()
            getWalletList()
            checkedIndex.value = 0
          } else {
            Toast('充值成功')
            setTimeout(() => {
              const isSetting = hasPayPassword.value ? 0 : 1
              uni.navigateTo({
                url:
                  '/pagesWallet/paymentPassword/paymentPassword?isSetting=' +
                  isSetting +
                  '&isBack=1',
              })
            }, 500)
          }
          loading.value = false
        },
        fail: (error) => {
          console.log(error)
        },
        complete: (complete) => {
          loading.value = false
        },
      })
    } else {
      loading.value = false
    }
  } else if (res.code == 232) {
    getBalance()
    getWalletList()
    checkedIndex.value = 0
    loading.value = false
    Toast(res.msg || '当前储值活动已失效')
  } else {
    loading.value = false
  }
  // 创建订单号
  // 调起支付
}

function goBack() {
  uni.navigateBack()
}
const currentItem = computed(() => {
  return datalist.value[checkedIndex.value] || {}
})

function jumpPath() {
  uni.navigateTo({
    url: '/pagesWallet/rechargeAgreement/rechargeAgreement',
  })
}
onLoad(() => {
  const res = uni.getMenuButtonBoundingClientRect() //获取胶囊
  top.value = res.top + 'px'
  pageheight.value = res.height + 10 + res.top + 'px'
  height.value = res.height + 'px'
  console.log('获取胶囊位置', height.value)
})
onShow(() => {
  getHasPayPassword()
  getBalance()
  getWalletList()
  checkedIndex.value = 0
})
</script>
<template>
  <view class="container" :style="`background-image: url(${activityImg});`">
    <view class="tab_set">
      <!-- 设置胶囊顶部 -->
      <view class="MenuButton_top"></view>
      <!-- 实际导航栏 可封装自定义组件  -->
      <view class="back_Tag">
        <uni-icons type="left" size="22" color="#00000090" @click="goBack"></uni-icons
        ><text class="title">我的钱包</text></view
      >
    </view>
    <view class="walletContent">
      <image src="/static/images/wallet/walletBg.png" class="walletBg" mode="scaleToFill" />
      <view class="walletCenter">
        <view class="walletCenter_l">
          <view class="walletTop">
            <text class="label">账户余额</text>
            <image
              class="eyeIcon"
              @click="isOpen = !isOpen"
              :src="isOpen ? `/static/images/eye-open2.png` : `/static/images/eye-close2.png`"
            />
          </view>
          <text class="walletCenter_l_money">{{ balanceInfo.totalBalance }}</text>
        </view>
        <view class="walletCenter_r">
          <view class="item detail" @click="goRecords"> 明细 </view>
          <view class="item" @click="goPayPassword"> 支付密码 ></view>
        </view>
      </view>
      <view class="walletBottom" v-if="isOpen">
        <view class="item">
          <text class="value">{{ balanceInfo.balance }}</text>
          <text>储值余额</text>
        </view>
        <view class="item">
          <text class="value">{{ balanceInfo.giftGold }}</text>
          <text>赠送消费金</text>
        </view>
      </view>
    </view>
    <view class="rechargeContent">
      <view v-if="datalist.length > 0">
        <view class="header">储值金额</view>
        <view class="list">
          <view
            class="item-wrapper"
            v-for="(item, index) in datalist"
            :key="item.id"
            @click="handleChecked(index)"
          >
            <!-- <image
              v-show="checkedIndex === index"
              class="duiicon"
              :src="`/static/images/duiicon.png`"
            /> -->
            <!-- 首充 -->
            <!-- <view
              class="shouchong"
              v-if="firstStoredActivity?.type === 1 && balanceInfo.firstStored && !item.activityTag"
            >
              <image src="/static/images/shouchong-bg.png" />
              <view class="text"> 首充 </view>
            </view> -->
            <!-- 活动 -->
            <!-- <view class="shouchong" v-if="item.activityTag">
              <image src="/static/images/chuzhi-bg.png" />
              <view class="text">{{ item?.activityTag }}</view>
            </view> -->
            <view class="item-bg">
              <image class="bg" :src="`/static/images/wallet/coupon_${item.money}.png`" />
              <view class="item" :class="checkedIndex === index ? 'active' : ''">
                <view class="number"><text class="icon">￥</text>{{ item?.money }}</view>
                <text class="label">赠{{ item?.giftGold }}元</text>
                <text class="label" v-if="firstStoredActivity?.giftGold && balanceInfo.firstStored"
                  >首充加赠{{ firstStoredActivity?.giftGold }}元</text
                >
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="noData" v-if="!datalist.length">
        <image
          src="https://yuefanpai.oss-cn-hangzhou.aliyuncs.com/miniapp/no-activity.png"
        />
      </view>
    </view>
    <view
      class="rechargeCoupon"
      v-show="
        (currentItem.marCouponId || (firstStoredActivity.marCouponId && balanceInfo.firstStored)) &&
        datalist.length
      "
    >
      <view class="header">额外储值权益</view>
      <view class="list">
        <view class="item">
          <!-- 首充 -->
          <view
            class="top_l"
            v-if="
              !currentItem.extraStoredTag &&
              firstStoredActivity.type === 1 &&
              balanceInfo.firstStored
            "
            >首次储值特惠</view
          >
          <image class="couponsBg" src="/static/images/wallet/couponBg.png" />
          <!-- 活动 -->
          <view class="top_l" v-if="currentItem.extraStoredTag">{{
            currentItem.extraStoredTag
          }}</view>
          <image class="top-r" src="" />

          <view class="coupons">
            <view class="coupon" v-if="currentItem?.marCouponId"
              >赠{{ currentItem?.marCouponName }}{{ currentItem?.marCouponCount }}张</view
            >
            <view class="coupon" v-if="firstStoredActivity?.marCouponId && balanceInfo.firstStored"
              >首充赠{{ firstStoredActivity?.marCouponName
              }}{{ firstStoredActivity?.marCouponCount }}张</view
            >
          </view>
        </view>
      </view>
    </view>
    <view class="footer">
      <view class="userAgreement">
        <view @click="iconSwiper" class="text">
          <view class="iconfont" :class="classIcon"></view>我已阅读并同意麦德范
        </view>
        <navigator
          hover-class="none"
          url="/pagesWallet/rechargeAgreement/rechargeAgreement"
          class="text_one"
          >《储值协议》</navigator
        >
      </view>
      <button
        class="rechargeButton"
        :class="datalist.length ? '' : 'noContent'"
        @click="handleRecharge"
        :loading="loading"
        :disabled="!datalist.length || loading"
      >
        立即充值
      </button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.container {
  background: #f8f8f8;
  width: 100vw;
  height: 516rpx;
  position: relative;
  background-size: 100% 516rpx;
  background-repeat: no-repeat;
  .walletContent {
    background-color: #feac16;
    margin: 30rpx;
    width: 690rpx;
    height: 280rpx;
    border-radius: 20rpx;
    padding: 60rpx;
    position: relative;
    .walletBg {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
    }
  }
  .walletCenter {
    display: flex;
    justify-content: space-between;
    position: relative;
    .walletCenter_l {
      display: flex;
      flex-direction: column;
      .walletTop {
        display: flex;
        align-items: center;
        color: #fff;
        .eyeIcon {
          width: 40rpx;
          height: 36rpx;
          margin-left: 10rpx;
        }
      }
      .walletCenter_l_money {
        .icon {
          font-size: 36rpx;
          font-weight: 700;
        }
        color: #fff;
        // font-family: DIN;
        font-size: 60rpx;
        font-style: normal;
        font-weight: 500;
        line-height: normal;
        vertical-align: bottom;
      }
    }
    .walletCenter_r {
      display: flex;
      align-items: center;
      flex-direction: column;
      .item {
        display: flex;
        flex-direction: column;
        align-items: center;
        color: rgba(255, 255, 255, 0.5);
        font-size: 26rpx;
        &.detail {
          width: 168rpx;
          height: 60rpx;
          line-height: 60rpx;
          border-radius: 100rpx;
          border: 2rpx solid #ffffff;
          font-size: 30rpx;
          margin-bottom: 10rpx;
          color: #fff;
        }
      }
    }
  }
  .walletBottom {
    display: flex;
    align-items: center;
    position: relative;
    .item {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      margin-right: 64rpx;
      font-size: 24rpx;
      color: #fff;
      .value {
        font-size: 32rpx;
        .icon {
          font-size: 32rpx;
        }
      }
    }
  }

  .rechargeContent {
    padding: 24rpx 30rpx;
    width: 690rpx;
    margin: 20rpx 30rpx;
    background-color: #fff;
    border-radius: 20rpx;
    box-shadow: 0rpx 4rpx 198rpx 2rpx rgba(0, 0, 0, 0.05);
    .header {
      color: #000000;
      text-align: center;
      font-family: 'PingFang SC';
      font-size: 30rpx;
      font-style: normal;
      font-weight: 600;
      line-height: normal;
      text-align: left;
      margin-bottom: 30rpx;
    }
    .list {
      display: flex;
      align-items: center;
      overflow-x: auto;
      justify-content: flex-start;
      &::-webkit-scrollbar {
        display: none !important;
        width: 0;
        height: 0;
        color: transparent;
      }
      .item-wrapper {
        height: 144rpx;
        position: relative;
        .duiicon {
          position: absolute;
          bottom: -10rpx;
          left: 86rpx;
          width: 40rpx;
          height: 40rpx;
          z-index: 98;
        }
        .shouchong {
          position: absolute;
          z-index: 2;
          top: 0;
          left: 46rpx;
          width: 104rpx;
          height: 36rpx;
          text-align: center;
          image {
            width: 104rpx;
            height: 36rpx;
            position: absolute;
            left: 0;
            bottom: -4rpx;
            z-index: -1;
          }
          .text {
            color: #fff;
            font-family: 'PingFang SC';
            font-size: 24rpx;
            font-style: normal;
            font-weight: 400;
            line-height: 40rpx;
            transform: rotate(-6deg);
          }
        }
      }
      .item {
        display: flex;
        width: 192rpx;
        height: 144rpx;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        flex-shrink: 0;
        border-radius: 32rpx;
        overflow-y: auto;
        position: absolute;
        top: 0;
        z-index: 8;
        .number {
          .icon {
            font-size: 32rpx;
            font-weight: normal;
          }
          color: #fff;
          text-align: center;
          font-size: 52rpx;
          font-style: normal;
          font-weight: 700;
          line-height: normal;
        }
        .label {
          color: #fff;
          text-align: center;
          font-family: 'PingFang SC';
          font-size: 24rpx;
          font-style: normal;
          font-weight: 400;
          line-height: normal;
          margin-top: 20rpx;
        }
      }
      .item-wrapper:last-of-type {
        .item-bg {
          margin-right: 0;
        }
      }
      .item-bg {
        background-color: #fff;
        margin-right: 20rpx;
        border-radius: 32rpx;
        width: 192rpx;
        height: 144rpx;
        position: relative;
        .bg {
          width: 100%;
          height: 100%;
        }
      }
    }
    .noData {
      margin: 200rpx auto 0;
      width: 376rpx;
      height: 360rpx;
    }
  }
  .rechargeCoupon {
    padding: 24rpx 30rpx;
    width: 690rpx;
    margin: 20rpx 30rpx;
    background-color: #fff;
    border-radius: 20rpx;
    box-shadow: 0rpx 4rpx 198rpx 2rpx rgba(0, 0, 0, 0.05);
    .header {
      color: #000000;
      text-align: center;
      font-family: 'PingFang SC';
      font-size: 30rpx;
      font-style: normal;
      font-weight: 600;
      line-height: normal;
      text-align: left;
      margin-bottom: 30rpx;
    }
    .list {
      .item {
        width: 630rpx;
        min-height: 160rpx;
        padding: 44rpx 18rpx;
        border-radius: 20rpx;
        background: #fcc800;
        position: relative;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        justify-content: center;
        .top_l {
          position: absolute;
          top: 0;
          left: 0;
          padding: 6rpx 18rpx;
          border-radius: 0px 0px 24rpx 0px;
          color: #f45c02;
          text-align: center;
          font-family: 'PingFang SC';
          font-size: 24rpx;
          font-style: normal;
          font-weight: 400;
          line-height: normal;
        }
        .top-r {
          position: absolute;
          top: -4rpx;
          right: 0;
          width: 52rpx;
          height: 48rpx;
        }
        .couponsBg {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
        }
        .coupons {
          color: #fff;
          font-family: 'PingFang SC';
          font-size: 32rpx;
          font-weight: bold;
          line-height: normal;
          margin-top: 10rpx;
          position: relative;
        }
      }
    }
  }
}
// 整个导航栏样式
.tab_set {
  // background: linear-gradient(rgb(82, 82, 247), rgb(218, 218, 248));
  height: v-bind('pageheight');
  position: relative;

  // 上方距离空隙
  .MenuButton_top {
    height: v-bind('top');
  }

  // 内部导航栏
  .back_Tag {
    height: v-bind('height');
    line-height: v-bind('height');
    // font-size: 20px;
    font-weight: 700;
    margin-left: 10rpx;
    font-weight: 400;
    position: relative;
    .title {
      position: absolute;
      left: 50%;
      transform: translate3d(-50%, 0, 0);
      top: 0;
      height: v-bind('height');
      line-height: v-bind('height');
      width: 100%;
      text-align: center;
      z-index: 99px;
      width: 200rpx;
    }
  }
}
.footer {
  position: fixed;
  bottom: env(safe-area-inset-bottom);
  padding-bottom: 44rpx;
  width: 100%;
  left: 0;
  .rechargeButton {
    margin-top: 28rpx;
    width: 632rpx;
    height: 88rpx;
    border-radius: 44rpx;
    background: #8adf4b;
    box-shadow: 0px 5px 6.2px 0px #d8ffbb;
    color: #fff;
    text-align: center;
    font-family: 'PingFang SC';
    font-size: 30rpx;
    font-style: normal;
    font-weight: 400;
    line-height: 88rpx;
    text-align: center;
  }
  .noContent {
    border-radius: 44rpx;
    background: rgba(0, 0, 0, 0.15);
    box-shadow: none;
  }
}
.userAgreement {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 70rpx;
  font-size: 22rpx;
  color: #00000080;
  .text {
    display: flex;
    justify-content: center;
    align-items: center;
    .iconfont {
      margin-right: 10rpx;
      font-size: 28rpx;
    }
    .icon-checked {
      color: $uni-color-motif;
    }
  }
  .text_one {
    color: $uni-color-motif;
  }
}
</style>
